class RemoteControl {
    constructor() {
        this.initializeData();
        this.initializeEventListeners();
        this.startRealTimeUpdate();
    }

    initializeData() {
        // 初始化设备状态数据
        this.deviceStatus = {
            waterPump: {
                id: 'wp001',
                name: '主水泵',
                status: false,
                frequency: 35,  // 默认35Hz
                pressure: 2.5,  // 默认2.5MPa
                runtime: 156.5, // 累计运行时长
                dailyRuntime: 4.5, // 今日运行时长
                efficiency: 92,    // 设备效率
                lastMaintenance: '2024-03-15',
                maxFrequency: 50,  // 最大频率
                minFrequency: 20,  // 最小频率
                optimalFrequency: 35, // 最佳频率
                pressureRange: {    // 压力范围
                    min: 1.8,
                    max: 3.2,
                    optimal: 2.5
                }
            },
            fertilizer: {
                id: 'fz001',
                name: '施肥器',
                status: false,
                concentration: 15,  // 默认15%浓度
                remaining: 85,      // 剩余85%
                mixRatio: '1:100',  // 默认混合比例
                dailyUsage: 25,     // 今日用量(L)
                efficiency: 95,     // 设备效率
                lastMaintenance: '2024-03-10',
                maxConcentration: 30, // 最大浓度
                minConcentration: 5,  // 最小浓度
                optimalConcentration: 15, // 最佳浓度
                tankCapacity: 200,   // 储罐容量(L)
                mixRatioOptions: ['1:50', '1:100', '1:150', '1:200']
            },
            valves: [
                { 
                    id: 'v001', 
                    name: '1号阀门', 
                    status: false, 
                    flow: 0, 
                    area: '1号区域', 
                    totalFlow: 125.6,   // 累计流量
                    lastCheck: '2024-03-18',
                    maxFlow: 5.0,       // 最大流量
                    minFlow: 1.0,       // 最小流量
                    optimalFlow: 3.0,   // 最佳流量
                    areaSize: 2000      // 灌溉面积(平方米)
                },
                { 
                    id: 'v002', 
                    name: '2号阀门', 
                    status: false, 
                    flow: 0, 
                    area: '2号区域', 
                    totalFlow: 98.4, 
                    lastCheck: '2024-03-18',
                    maxFlow: 5.0,
                    minFlow: 1.0,
                    optimalFlow: 3.0,
                    areaSize: 1800
                },
                { 
                    id: 'v003', 
                    name: '3号阀门', 
                    status: false, 
                    flow: 0, 
                    area: '3号区域', 
                    totalFlow: 156.2, 
                    lastCheck: '2024-03-17',
                    maxFlow: 5.0,
                    minFlow: 1.0,
                    optimalFlow: 3.0,
                    areaSize: 2200
                },
                { 
                    id: 'v004', 
                    name: '4号阀门', 
                    status: false, 
                    flow: 0, 
                    area: '4号区域', 
                    totalFlow: 145.8, 
                    lastCheck: '2024-03-17',
                    maxFlow: 5.0,
                    minFlow: 1.0,
                    optimalFlow: 3.0,
                    areaSize: 1900
                }
            ],
            operationHistory: []
        };

        this.updateDeviceStatus();
    }

    initializeEventListeners() {
        // 监听设备控制按钮
        document.querySelectorAll('.device-control-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const deviceId = e.target.dataset.deviceId;
                const action = e.target.dataset.action;
                this.showConfirmDialog(deviceId, action);
            });
        });

        // 监听参数调节
        document.querySelectorAll('.parameter-control').forEach(control => {
            control.addEventListener('input', (e) => {
                const deviceId = e.target.dataset.deviceId;
                const parameter = e.target.dataset.parameter;
                const value = e.target.value;
                this.adjustParameter(deviceId, parameter, value);
            });
        });
    }

    showConfirmDialog(deviceId, action) {
        const device = this.getDeviceById(deviceId);
        const actionText = action === 'start' ? '启动' : '停止';
        
        if (confirm(`确定要${actionText}${device.name}吗？`)) {
            this.controlDevice(deviceId, action);
            this.addOperationHistory(deviceId, action);
            this.showFeedback(`已${actionText}${device.name}`);
        }
    }

    getDeviceById(deviceId) {
        if (deviceId.startsWith('wp')) return this.deviceStatus.waterPump;
        if (deviceId.startsWith('fz')) return this.deviceStatus.fertilizer;
        return this.deviceStatus.valves.find(v => v.id === deviceId);
    }

    showFeedback(message) {
        const feedback = document.createElement('div');
        feedback.className = 'operation-feedback';
        feedback.textContent = message;
        document.querySelector('.remote-control-panel').appendChild(feedback);
        
        setTimeout(() => feedback.remove(), 3000);
    }

    addOperationHistory(deviceId, action) {
        const device = this.getDeviceById(deviceId);
        const history = {
            time: new Date().toLocaleString(),
            device: device.name,
            action: action === 'start' ? '启动' : '停止',
            operator: '系统管理员'
        };
        
        this.deviceStatus.operationHistory.unshift(history);
        if (this.deviceStatus.operationHistory.length > 10) {
            this.deviceStatus.operationHistory.pop();
        }
    }

    updateDeviceStatus() {
        const panel = document.querySelector('.remote-control-panel .panel-content');
        if (!panel) return;

        panel.innerHTML = `
            <div class="control-section">
                <div class="section-header">
                    <h2><i class="fas fa-cogs"></i> 设备远程控制</h2>
                </div>

                <!-- 设备运行状态统计 -->
                <div class="status-overview">
                    <div class="status-card">
                        <div class="status-icon running">
                            <i class="fas fa-play-circle"></i>
                        </div>
                        <div class="status-info">
                            <h4>运行设备</h4>
                            <p class="status-value">${this.getRunningDevicesCount()}台</p>
                        </div>
                    </div>
                    <div class="status-card">
                        <div class="status-icon stopped">
                            <i class="fas fa-stop-circle"></i>
                        </div>
                        <div class="status-info">
                            <h4>停止设备</h4>
                            <p class="status-value">${this.getStoppedDevicesCount()}台</p>
                        </div>
                    </div>
                    <div class="status-card">
                        <div class="status-icon">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="status-info">
                            <h4>今日运行时长</h4>
                            <p class="status-value">${this.getTotalRuntime()}小时</p>
                        </div>
                    </div>
                    <div class="status-card">
                        <div class="status-icon">
                            <i class="fas fa-tint"></i>
                        </div>
                        <div class="status-info">
                            <h4>今日用水量</h4>
                            <p class="status-value">${this.getTotalWaterUsage()}m³</p>
                        </div>
                    </div>
                </div>

                <!-- 主要设备控制 -->
                <div class="main-devices">
                    <!-- 水泵控制 -->
                    <div class="device-card ${this.deviceStatus.waterPump.status ? 'running' : ''}">
                        <div class="device-header">
                            <h3><i class="fas fa-pump-medical"></i> ${this.deviceStatus.waterPump.name}</h3>
                            <span class="status-badge ${this.deviceStatus.waterPump.status ? 'running' : 'stopped'}">
                                <i class="fas ${this.deviceStatus.waterPump.status ? 'fa-play' : 'fa-stop'}"></i>
                                ${this.deviceStatus.waterPump.status ? '运行中' : '已停止'}
                            </span>
                        </div>
                        <div class="device-params">
                            <div class="param-item">
                                <span class="param-label">运行频率</span>
                                <span class="param-value">${this.deviceStatus.waterPump.frequency} Hz</span>
                                <input type="range" class="parameter-control" 
                                    data-device-id="${this.deviceStatus.waterPump.id}"
                                    data-parameter="frequency"
                                    min="0" max="50" value="${this.deviceStatus.waterPump.frequency}">
                            </div>
                            <div class="param-item">
                                <span class="param-label">系统压力</span>
                                <span class="param-value">${this.deviceStatus.waterPump.pressure} MPa</span>
                            </div>
                            <div class="param-item">
                                <span class="param-label">运行时长</span>
                                <span class="param-value">${this.deviceStatus.waterPump.runtime.toFixed(1)} 小时</span>
                            </div>
                            <div class="param-item">
                                <span class="param-label">设备效率</span>
                                <span class="param-value">${this.deviceStatus.waterPump.efficiency}%</span>
                            </div>
                        </div>
                        <div class="device-controls">
                            <button class="device-control-btn ${this.deviceStatus.waterPump.status ? 'stop' : 'start'}"
                                data-device-id="${this.deviceStatus.waterPump.id}"
                                data-action="${this.deviceStatus.waterPump.status ? 'stop' : 'start'}">
                                <i class="fas ${this.deviceStatus.waterPump.status ? 'fa-stop' : 'fa-play'}"></i>
                                ${this.deviceStatus.waterPump.status ? '停止' : '启动'}
                            </button>
                        </div>
                        <div class="device-info">
                            <p>上次维护：${this.deviceStatus.waterPump.lastMaintenance}</p>
                        </div>
                    </div>

                    <!-- 施肥器控制 -->
                    <div class="device-card ${this.deviceStatus.fertilizer.status ? 'running' : ''}">
                        <div class="device-header">
                            <h3><i class="fas fa-flask"></i> ${this.deviceStatus.fertilizer.name}</h3>
                            <span class="status-badge ${this.deviceStatus.fertilizer.status ? 'running' : 'stopped'}">
                                <i class="fas ${this.deviceStatus.fertilizer.status ? 'fa-play' : 'fa-stop'}"></i>
                                ${this.deviceStatus.fertilizer.status ? '运行中' : '已停止'}
                            </span>
                        </div>
                        <div class="device-params">
                            <div class="param-item">
                                <span class="param-label">肥料浓度</span>
                                <span class="param-value">${this.deviceStatus.fertilizer.concentration}%</span>
                                <input type="range" class="parameter-control"
                                    data-device-id="${this.deviceStatus.fertilizer.id}"
                                    data-parameter="concentration"
                                    min="0" max="100" value="${this.deviceStatus.fertilizer.concentration}">
                            </div>
                            <div class="param-item">
                                <span class="param-label">肥料余量</span>
                                <span class="param-value">${this.deviceStatus.fertilizer.remaining}%</span>
                            </div>
                            <div class="param-item">
                                <span class="param-label">混合比例</span>
                                <span class="param-value">${this.deviceStatus.fertilizer.mixRatio}</span>
                            </div>
                            <div class="param-item">
                                <span class="param-label">设备效率</span>
                                <span class="param-value">${this.deviceStatus.fertilizer.efficiency}%</span>
                            </div>
                        </div>
                        <div class="device-controls">
                            <button class="device-control-btn ${this.deviceStatus.fertilizer.status ? 'stop' : 'start'}"
                                data-device-id="${this.deviceStatus.fertilizer.id}"
                                data-action="${this.deviceStatus.fertilizer.status ? 'stop' : 'start'}">
                                <i class="fas ${this.deviceStatus.fertilizer.status ? 'fa-stop' : 'fa-play'}"></i>
                                ${this.deviceStatus.fertilizer.status ? '停止' : '启动'}
                            </button>
                        </div>
                        <div class="device-info">
                            <p>上次维护：${this.deviceStatus.fertilizer.lastMaintenance}</p>
                        </div>
                    </div>
                </div>

                <!-- 阀门控制 -->
                <div class="valves-control">
                    <h3><i class="fas fa-faucet"></i> 阀门控制</h3>
                    <div class="valves-grid">
                        ${this.deviceStatus.valves.map(valve => `
                            <div class="valve-card ${valve.status ? 'running' : ''}">
                                <div class="valve-header">
                                    <h4>${valve.name}</h4>
                                    <span class="status-badge ${valve.status ? 'running' : 'stopped'}">
                                        ${valve.status ? '已开启' : '已关闭'}
                                    </span>
                                </div>
                                <div class="valve-info">
                                    <div class="info-item">
                                        <span class="info-label">所属区域</span>
                                        <span class="info-value">${valve.area}</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">实时流量</span>
                                        <span class="info-value">${valve.flow} m³/h</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">累计流量</span>
                                        <span class="info-value">${valve.totalFlow} m³</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">上次检查</span>
                                        <span class="info-value">${valve.lastCheck}</span>
                                    </div>
                                </div>
                                <div class="valve-controls">
                                    <button class="device-control-btn ${valve.status ? 'stop' : 'start'}"
                                        data-device-id="${valve.id}"
                                        data-action="${valve.status ? 'stop' : 'start'}">
                                        <i class="fas ${valve.status ? 'fa-stop' : 'fa-play'}"></i>
                                        ${valve.status ? '关闭' : '开启'}
                                    </button>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>

                <!-- 操作历史记录 -->
                <div class="operation-history">
                    <h3><i class="fas fa-history"></i> 操作历史</h3>
                    <div class="history-list">
                        ${this.deviceStatus.operationHistory.map(history => `
                            <div class="history-item">
                                <span class="history-time">${history.time}</span>
                                <span class="history-content">
                                    <span class="operator">${history.operator}</span>
                                    ${history.action}了
                                    <span class="device-name">${history.device}</span>
                                </span>
                            </div>
                        `).join('')}
                    </div>
                </div>
            </div>
        `;

        this.initializeEventListeners();
    }

    getRunningDevicesCount() {
        let count = 0;
        if (this.deviceStatus.waterPump.status) count++;
        if (this.deviceStatus.fertilizer.status) count++;
        this.deviceStatus.valves.forEach(valve => {
            if (valve.status) count++;
        });
        return count;
    }

    getStoppedDevicesCount() {
        return 6 - this.getRunningDevicesCount(); // 总共6个设备
    }

    getTotalRuntime() {
        return (this.deviceStatus.waterPump.dailyRuntime + this.deviceStatus.fertilizer.dailyRuntime).toFixed(1);
    }

    getTotalWaterUsage() {
        return this.deviceStatus.valves.reduce((total, valve) => total + valve.totalFlow, 0).toFixed(1);
    }

    controlDevice(deviceId, action) {
        // 模拟设备控制
        if (deviceId.startsWith('wp')) {
            this.deviceStatus.waterPump.status = action === 'start';
        } else if (deviceId.startsWith('fz')) {
            this.deviceStatus.fertilizer.status = action === 'start';
        } else if (deviceId.startsWith('v')) {
            const valve = this.deviceStatus.valves.find(v => v.id === deviceId);
            if (valve) {
                valve.status = action === 'start';
            }
        }

        // 更新界面
        this.updateDeviceStatus();
    }

    adjustParameter(deviceId, parameter, value) {
        // 模拟参数调节
        if (deviceId.startsWith('wp')) {
            if (parameter === 'frequency') {
                this.deviceStatus.waterPump.frequency = parseInt(value);
            }
        } else if (deviceId.startsWith('fz')) {
            if (parameter === 'concentration') {
                this.deviceStatus.fertilizer.concentration = parseInt(value);
            }
        }

        // 更新界面
        this.updateDeviceStatus();
    }

    startRealTimeUpdate() {
        // 每5秒更新一次数据
        setInterval(() => {
            // 模拟数据变化
            if (this.deviceStatus.waterPump.status) {
                // 更新运行时间
                this.deviceStatus.waterPump.runtime += 5/3600;
                this.deviceStatus.waterPump.dailyRuntime += 5/3600;
                
                // 根据频率计算压力波动范围
                const frequency = this.deviceStatus.waterPump.frequency;
                const pressureBase = 1.5 + (frequency / 50) * 1.5; // 频率越高，基础压力越大
                const fluctuation = 0.2; // 压力波动范围
                this.deviceStatus.waterPump.pressure = (pressureBase + (Math.random() * fluctuation - fluctuation/2)).toFixed(2);
            }

            if (this.deviceStatus.fertilizer.status) {
                // 更新肥料余量，考虑浓度因素
                const concentration = this.deviceStatus.fertilizer.concentration;
                const consumptionRate = (concentration / 100) * 0.2; // 浓度越高，消耗越快
                this.deviceStatus.fertilizer.remaining = Math.max(0, this.deviceStatus.fertilizer.remaining - consumptionRate);
                this.deviceStatus.fertilizer.dailyRuntime += 5/3600;
                
                // 更新日用量
                this.deviceStatus.fertilizer.dailyUsage += consumptionRate * 0.5;
            }

            this.deviceStatus.valves.forEach(valve => {
                if (valve.status) {
                    // 根据区域大小计算基础流量
                    const baseFlow = (valve.areaSize / 2000) * valve.optimalFlow;
                    const fluctuation = 0.3; // 流量波动范围
                    const flow = (baseFlow + (Math.random() * fluctuation - fluctuation/2)).toFixed(1);
                    
                    valve.flow = flow;
                    // 累计流量增加，考虑时间间隔
                    valve.totalFlow += parseFloat(flow) * 5/3600;
                } else {
                    valve.flow = 0;
                }
            });

            this.updateDeviceStatus();
        }, 5000);
    }
}

// 创建远程控制实例
window.remoteControl = new RemoteControl(); 